package cn.edu.dgut.css.sai.restfulsvc;

import cn.edu.dgut.css.sai.restfulsvc.entity.Customer;
import cn.edu.dgut.css.sai.restfulsvc.repository.CustomerRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 企业级软件开发-实训课程：Spring Boot 2.2.2
 *
 * @author 黎志雄
 * 2019-12-12
 */
@SpringBootApplication
public class RESTfulSvcApplication {

    public static void main(String[] args) {
        SpringApplication.run(RESTfulSvcApplication.class, args);
    }

}

@SuppressWarnings("unused")
@Configuration
@Slf4j
class initDataSource {
    //    @Bean
    // lambda表达式的返回值： 是实现(implements)这个函数式接口的匿名内部类的实例对象。
    public CommandLineRunner commandLineRunner(CustomerRepository customerRepository, ResourceLoader resourceLoader) {
        return args -> {
            // 读取类路径下的文件
            // 有时会提示找不到文件，这时刷新一下idea的maven面板
            // 生成模拟数据：https://mockaroo.com/
            Resource resource = resourceLoader.getResource("classpath:MOCK_DATA.csv");
//             Resource resource = new ClassPathResource("MOCK_DATA.csv");

            // 计时
            long start = System.currentTimeMillis();
            List<Customer> users = parseCSVFile(resource);
            log.info("保存了 Customer 的数目为: {} , 当前线程名称是：{}", users.size(), "" + Thread.currentThread().getName());

            customerRepository.saveAll(users);

            long end = System.currentTimeMillis();
            log.info("耗时: {} 毫秒.", (end - start));
            // http://localhost:9088/restapi/h2-console
            // jdbc:h2:mem:testdb
            // sa
            // 密码不用填
        };
    }

    private List<Customer> parseCSVFile(final Resource Resource) throws Exception {
        final List<Customer> users = new ArrayList<>();
        try {
            // jdk7的try资源句式
            try (final BufferedReader br = new BufferedReader(new InputStreamReader(Resource.getInputStream()))) {
                // jdk8的Stream遍历 输入流的行
                br.lines().forEach(line -> {
                    final String[] data = line.split(",");
                    final Customer user = new Customer();
                    // data[0]是id，不需要设置。
                    user.setCustomerName(data[1]);
                    user.setDateofBirth(LocalDate.parse(data[2]));// 字符串 转 Localdate
                    user.setPhoneNumber(data[3]);
                    users.add(user);
                });
                return users;
            }
        } catch (final IOException e) {
            log.error("转换 CSV file 失败 {0}", e);
            throw new Exception("转换 CSV file 失败{}", e);
        }
    }
}
